<?php

CRequireIfPHP4('CObject');

if (!class_exists('_CError')) {
	if (CIsPHP4())
		require_once '_CError-PHP4.php';
	else
		require_once '_CError-PHP5.php';
}

/* common error codes */
define ('kCMalformedData', 'kCMalformedData');
define ('kCMultipleErrors', 'kCMultipleErrors');
define ('kCFileNotFound', 'kCFileNotFound');
define ('kCIOError', 'kCIOError');

/* safe to copy */
class CError extends _CError {
	var $Code;
	var $Message;
	var $Reason;
	
	function Init($code, $message, $reason = null) {
		$this->Code = $code;
		$this->Message = $message;
		$this->Reason = $reason;
	}
	
	function Description() {
		$s = "Error with code {$this->Code}: '{$this->Message}'";
		if (CErr($this->Reason))
			$s .= "\nCaused by another error: " . $this->Reason->Description();
		
		return $s;
	}
	
	function MalformedData($reason) {
		// returns a default error for malformed data.
		return new CError(kCMalformedData, "The data being transformed or read is of the wrong type or in the wrong format.", $reason);
	}
	
	function MultipleErrors($reasons) {
		// returns an error that has an array of errors as its reasons.
		return new CMultipleErrors($reasons);
	}
	
	function FileNotFound($name, $reason) {
		// returns a default "file not found" error.
		return new CError(kCFileNotFound, "The file named '$name' was not found.", $reason);
	}
	
	function IOError($reason) {
		// returns a default "I/O error".
		return new CError(kCIOError, "An I/O error occurred.", $reason);
	}	
	
	function TriedAllOf($what) {
		$errs = array();
		foreach ($what as $err) {
			if (CErr($err))
				$errs[] = $err;
		}
		
		if (sizeof($errs) == 0)
			return true;
		else if (sizeof($errs) == 1)
			return $errs[0];
		else
			return CError::MultipleErrors($errs);
	}
	
	function TryAll() {
		$w = func_get_args();
		return CError::TriedAllOf($w);
	}
}

class CMultipleErrors extends CError {
	function Init($reasons) {
		parent::Init(kCMultipleErrors, "More than one error has happened.", $reasons);
	}
	
	function Description() {
		$s = "Error with code {$this->Code}: '{$this->Message}'";
		foreach ($this->Reason as $reason)
			$s .= "\n -- \n" . $reason->Description() . "\n -- \n";
		
		return $s;
	}
}

?>